<?php
namespace app\admin\controller;

use think\Config;
use think\Controller;
use think\Db;
use think\Log;
use think\Session;

/**
 * 后台登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{
    /**
     * 后台登录
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 登录验证
     * @return string
     */
    public function login()
    {
        if ($this->request->isAjax()) {
            //$data            = $this->request->only(['username', 'password', 'verify']);
            $data            = $this->request->only(['username', 'password']);
            $validate_result = $this->validate($data, 'Login');

            if ($validate_result !== true) {
                return ajax_return_adv_error($validate_result);
            } else {
                $where['username'] = $data['username'];
                //$where['password'] = md5($data['password'] . Config::get('salt'));
                $admin_user = Db::name('admin_user')->field('id,username,status,password')->where($where)->find();
                if (!empty($admin_user) && ($admin_user['password'] == md5($data['password'] . Config::get('salt')))) {
                    if ($admin_user['status'] != 1) {
                        return ajax_return_adv_error('当前用户已被禁用！');
                    } else {
                        Session::set('admin_id', $admin_user['id']);
                        Session::set('admin_name', $admin_user['username']);
                        Db::name('admin_user')->update(
                            [
                                'last_login_time' => time(),
                                'last_login_ip'   => $this->request->ip(),
                                'id'              => $admin_user['id']
                            ]
                        );
                        return ajax_return_adv('登录成功！');
                    }
                } else {
                    return ajax_return_adv_error('用户名或密码错误！');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isAjax()) {
            Session::delete('admin_id');
            Session::delete('admin_name');
            return ajax_return_adv('退出成功');
        }
    }
}
